package com.enlorenz.core.channel.socket.common.reader.custom;

import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

import com.enlorenz.common.util.MessageBuffer;
import com.enlorenz.core.channel.socket.common.reader.INioReader;
import com.enlorenz.core.channel.socket.common.util.NioUtil;

public class AsciiMsgNioReader implements INioReader{
	private SocketChannel channel;
	private ByteBuffer commBuffer;
	
	public void setChannel(SocketChannel channel) {
		this.channel = channel;
	}

	public void setCommBuffer(ByteBuffer commBuffer) {
		this.commBuffer = commBuffer;
	}

	@Override
	public byte[] read()
			throws Exception {
		MessageBuffer messageBuffer=new MessageBuffer();
		byte [] msg=null;
		boolean isLegal=false;
		boolean isReadEnd=false;
		while(null!=(msg=NioUtil.read(channel, commBuffer,1))){
			byte b=msg[0];
			if(b == '*'){
				messageBuffer.append(msg);
				isLegal=true;
				continue;
			}else if(b == '#'){
				messageBuffer.append(msg);
				isReadEnd=true;
				break;
			}
			
			if(isLegal){
				messageBuffer.append(msg);
			}
		}
		
		byte [] output=messageBuffer.toByte();
		
		if(isLegal && isReadEnd && null!=output){
			return output;
		}else{
			return null;
		}
		
	}
}
